package com.example.controller;

import com.example.config.KieSessionUtils;
import com.example.config.ServiceMQTT;
import com.example.mapper.*;
import com.example.pojo.Runtime.omRuntimeDtl;
import com.example.pojo.SeRuleFile;
import com.example.pojo.dev.icDevPoint;
import com.example.pojo.msgDevice;
import com.example.pojo.DroolsTest;
import com.example.pojo.Runtime.OmDrools;
import com.example.pojo.alarm.alarmMessage;
import com.example.pojo.alarm.messageRemind;
import com.example.pojo.dev.fmDevInfo;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: drools
 * @BelongsPackage: com.example.controller
 * @Author: dyz
 * @CreateTime: 16:59
 * @Version: 1.0
 */
@Component
public class MaintainDrools implements CommandLineRunner {


    static String FileType = "类型,实例";
    // @Autowired
    static public FileMapper fileMapper;

    @Autowired
    public void fileMapper(FileMapper fileMapper) {
        MaintainDrools.fileMapper = fileMapper;
    }

    //  @Autowired
    static public omMapper omMapper;

    @Autowired
    public void infoMapper(omMapper omMapper) {
        MaintainDrools.omMapper = omMapper;
    }

    static public ServiceMQTT serviceMQTT;

    @Autowired
    public void serviceMQTT(ServiceMQTT serviceMQTT) {
        MaintainDrools.serviceMQTT = serviceMQTT;
    }

    static public infoMapper infoMapper;

    @Autowired
    public void infoMapper(infoMapper infoMapper) {
        MaintainDrools.infoMapper = infoMapper;
    }

    static public PointEqipmentMapper pointEqipmentMapper;

    @Autowired
    public void pointEqipmentMapper(PointEqipmentMapper pointEqipmentMapper) {
        MaintainDrools.pointEqipmentMapper = pointEqipmentMapper;
    }

    static public AlarmMapper alarmMapper;

    @Autowired
    public void alarmService(AlarmMapper alarmMapper) {
        MaintainDrools.alarmMapper = alarmMapper;
    }

    static public MessageRemindMapper messageRemindMapper;

    @Autowired
    public void MessageRemindMapper(MessageRemindMapper messageRemindMapper) {
        MaintainDrools.messageRemindMapper = messageRemindMapper;
    }

    static SimpleDateFormat sdf01 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Value("${web.upload}")
    private String upload;

    static KieHelper kieHelpertype;

    static KieHelper kieHelperexample;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void run(String... args) throws Exception {
        this.updatekieHepler();

    }

    public void updatekieHepler() {
        String[] split = FileType.split(",");
        //修改规则 可能绑定了 数据
        Date date = new Date();
        KieHelper kieHelper = new KieHelper();

        for (String typename : split) {
            List<SeRuleFile> seRuleFiles = fileMapper.selectAllbytyp(typename, "保养");
            if (seRuleFiles.size() == 0) {
                if (typename.equals("类型")) {
                    kieHelpertype = null;
                } else {
                    kieHelperexample = null;
                }
            } else {
                for (SeRuleFile seRuleFile : seRuleFiles) {
                    try {
                        //获取规则文件
                        String dRl = KieSessionUtils.getDRl(upload + seRuleFile.getUrl());
                        if (typename.equals("类型")) {
                            kieHelpertype = kieHelper.addContent(dRl, ResourceType.DRL);
                        } else {
                            kieHelperexample = kieHelper.addContent(dRl, ResourceType.DRL);
                        }
                        //kieSession = kieHelper1.build().newKieSession();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //@Scheduled(cron = "0 0 0 * * ?")
    @Scheduled(cron = "0 30 8 * * *")
    // @Scheduled(fixedDelay = 1000 * 20)
    private void Runtime() throws MqttException, ParseException {
        List<msgDevice> maintainmsg = alarmMapper.getbyalarmStatusandmsgType();
        for (msgDevice msgDevice : maintainmsg) {
            alarmMapper.delectbyid(msgDevice.getId());
        }
        //将有单个判断的设备取出
        List<SeRuleFile> exampleseRuleFiles = fileMapper.selectAllbytyp("实例", "保养");
        List<SeRuleFile> typeseRuleFiles = fileMapper.selectAllbytyp("类型", "保养");


        //查找所有的设备
        List<icDevPoint> devName = pointEqipmentMapper.disNamedbId();
        //拿到所有带变量的设备   运行时长用
        ArrayList<omRuntimeDtl> omRuntimedtlsAndvar = new ArrayList<>();
//寿命到期 保养周期
        List<omRuntimeDtl> maintainvars = new ArrayList<>();
//      for (icDevPoint dev : devName) {
//          boolean maintain=true;
//          omRuntimeDtl maintainvar = new omRuntimeDtl();
//          maintainvar.setDbid(dev.getDbid());
//          maintainvar.setName(dev.getDeviceName()+" "+dev.getDevNumber());
//          maintainvar.setModelId(Integer.valueOf(dev.getModelId()));
//      }


        for (icDevPoint dev : devName) {

            //查询设备的测点
            List<String> pointName = omMapper.dispointName(dev.getDbid());
            for (String string : pointName) {
                //    boolean maintain=true;
//               omRuntimeDtl maintainvar = new omRuntimeDtl();
//               maintainvar.setDbid(dev.getDbid());
//               maintainvar.setName(dev.getDeviceName()+" "+dev.getDevNumber());
//               maintainvar.setModelId(Integer.valueOf(dev.getModelId()));
                //查询变量
                List<omRuntimeDtl> disvarName = omMapper.disvarNameandvarid(string);
                for (omRuntimeDtl var : disvarName) {
                    omRuntimeDtl omRuntimedtlvar = new omRuntimeDtl();
                    omRuntimedtlvar.setDbid(dev.getDbid());
                    omRuntimedtlvar.setName(dev.getDevName() + " " + dev.getDevNumber());
                    omRuntimedtlvar.setModelId(Integer.valueOf(dev.getModelId()));
                    omRuntimedtlvar.setVariableName(var.getVariableName());
                    omRuntimedtlvar.setVarId(var.getVarId());
                    omRuntimedtlsAndvar.add(omRuntimedtlvar);
//                   if (maintain && var.getVariableName().contains("运行状态") ){
//                       maintainvar.setVariableName(var.getVariableName());
//                       maintainvar.setVarId(var.getVarId());
//                       maintainvars.add(maintainvar);
//                       maintain=false;
//                   }
                }
//               //说明绑定的变量里没有包含运行状态用第一个
//               if (maintainvar.getVariableName()==null && devName!=null && disvarName.size()!=0){
//                   maintainvar.setVariableName(disvarName.get(0).getVariableName());
//                   maintainvar.setVarId(disvarName.get(0).getVarId());
//                   maintainvars.add(maintainvar);
//               }

            }
            //获取保养周期 寿命到期时长
            List<icDevPoint> pointEquipments = pointEqipmentMapper.selectVaridbymainrunVariable(dev.getDbid());
            for (icDevPoint pointEquipment : pointEquipments) {
                omRuntimeDtl maintainvar = new omRuntimeDtl();
                maintainvar.setDbid(dev.getDbid());
                maintainvar.setName(dev.getDevName() + " " + dev.getDevNumber());
                maintainvar.setModelId(Integer.valueOf(dev.getModelId()));
                maintainvar.setVariableName(pointEquipment.getVarName());
                maintainvar.setVarId(pointEquipment.getVarId());
                maintainvars.add(maintainvar);
            }

//distinct name ,db_id ,model_id,variable_name

        }

        //有单个规则的设备 带变量 运行时长
        List<omRuntimeDtl> varexample = new ArrayList<>();
        for (SeRuleFile seRuleFile : exampleseRuleFiles) {
            for (omRuntimeDtl dev : omRuntimedtlsAndvar) {
                if (seRuleFile.getFilename().contains(dev.getName())) {
                    varexample.add(dev);
                }
            }
        }
        //没有单个规则的设备 带变量 运行时长
        List<omRuntimeDtl> vartype = new ArrayList<>();
        for (SeRuleFile seRuleFile : typeseRuleFiles) {
            for (omRuntimeDtl dev : omRuntimedtlsAndvar) {
                if (dev.getName().contains(seRuleFile.getFilename())) {
                    vartype.add(dev);
                }
            }
        }
////没有单个规则的设备 带变量 运行时长
//        List<omRuntimeDtl> vartype = omRuntimedtlsAndvar.stream().filter(item -> exampleseRuleFilesseRuleFiles.stream().allMatch(each ->
//                !each.getFilename().contains(item.getName()))).collect(Collectors.toList());


        //寿命到期 保养  单个
        List<omRuntimeDtl> example = new ArrayList<>();
        List<omRuntimeDtl> maintainexample = new ArrayList<>();
        for (SeRuleFile seRuleFile : exampleseRuleFiles) {

            omRuntimeDtl omRuntimeDtl = new omRuntimeDtl();
            omRuntimeDtl.setDbid(seRuleFile.getDbid());
            omRuntimeDtl.setModelId(seRuleFile.getModelId());
            omRuntimeDtl.setName(seRuleFile.getFilename());
            example.add(omRuntimeDtl);
            for (omRuntimeDtl dev : maintainvars) {
                if (seRuleFile.getFilename().contains(dev.getName())) {
                    maintainexample.add(dev);
                }
            }
        }

        //寿命到期 保养
        List<omRuntimeDtl> type = maintainvars.stream().filter(item -> exampleseRuleFiles.stream().allMatch(each -> !each.getFilename().contains(item.getName()))).collect(Collectors.toList());

        //模糊匹配   运行时长 保养周期  寿命到期 保修到期

        this.runtimekie(vartype, kieHelpertype);
        this.maintainkie(type, kieHelpertype);
        this.EndofLifetype(type, kieHelpertype);
        this.maintenancetype(type, kieHelpertype);
        //单个设备匹配
        this.runtimekie(varexample, kieHelperexample);
        this.maintainkie(maintainexample, kieHelperexample);
        this.EndofLifeexample(example, kieHelperexample);
        this.maintenanceexample(example, kieHelperexample);


        //   List<omRuntimeDtl> devnameList = omMapper.disNameanddbid();

//      //寿命到期 保养
//      List <omRuntimeDtl> example=new ArrayList<>();
//      for (SeRuleFile seRuleFile : exampleseRuleFilesseRuleFiles) {
//          for (omRuntimeDtl dev : devnameList) {
//              if (seRuleFile.getFilename().contains(dev.getName())){
//                  example.add(dev);
//              }
//          }
//      }


//      //寿命到期 保养
//      List <omRuntimeDtl>type = devnameList.stream().filter(item -> exampleseRuleFilesseRuleFiles.stream().allMatch(each ->
//              !each.getFilename().contains(item.getName()))).collect(Collectors.toList());

//       ArrayList<omRuntimeDtl> omRuntimedtls = new ArrayList<>();

        // List<omRuntimeDtl> devnameandpositionList = omMapper.disNameandposition();

        //        //没有单个规则的设备
//        List <omRuntimeDtl> positiontype = devnameandpositionList.stream().filter(item -> exampleseRuleFilesseRuleFiles.stream().allMatch(each ->
//                !each.getFilename().contains(item.getName()))).collect(Collectors.toList());
        //模糊匹配   运行时长 寿命到期
//      this.runtimekie(positiontype,kieHelpertype);
//        this.maintainkie(type,kieHelpertype);
//        this.EndofLife(type,kieHelpertype);
//        for (omRuntimeDtl omRuntimedtl : type) {
//            Double aDouble = omMapper.selectdevRuntime(omRuntimedtl.getDbid());
//            DroolsTest droolsTest = new DroolsTest();
//            //如果一条规则判断完成之后不关闭会导致 之后的规则全部能通过
//            KieSession kieSession = kieHelpertype.build().newKieSession();
//
//            droolsTest.setPointName(omRuntimedtl.getName());
//            droolsTest.setKey("运行时长");
//            droolsTest.setValue(Float.valueOf(String.valueOf(aDouble)));
//            droolsTest.setDbId(omRuntimedtl.getDbid());
////            droolsTest.setSingal((String) Beanmap.get("dbid"));
//            kieSession.insert(droolsTest);
//        }


//        //有单个规则的设备
//        List <omRuntimeDtl> positionexample=new ArrayList<>();
//            for (SeRuleFile seRuleFile : exampleseRuleFilesseRuleFiles) {
//                for (omRuntimeDtl dev : devnameandpositionList) {
//                    if (seRuleFile.getFilename().contains(dev.getName())){
//                        positionexample.add(dev);
//                    }
//                }
//            }


        //  this.runtimekie(positionexample,kieHelperexample);
//        this.maintainkie(example,kieHelperexample);
//        this.EndofLife(example,kieHelperexample);
//        for (omRuntimeDtl omRuntimedtl : example) {
//
//        }

    }

    public void maintainkie(List<omRuntimeDtl> onoffdtls, KieHelper kieHelper) throws MqttException {
        for (omRuntimeDtl omRuntimedtl : onoffdtls) {
            Date date = new Date();
            double aDouble = 0.0;
            //查询这个设备的置购日期  不需要了
            fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(omRuntimedtl.getDbid()), String.valueOf(omRuntimedtl.getModelId()));
            omRuntimeDtl datalimit1bydbid = omMapper.getDatalimit1byvarId(omRuntimedtl.getVarId());
            if (null != fmDeviceinfo && null != fmDeviceinfo.getPurchaseDate() && StringUtils.isNotBlank(fmDeviceinfo.getPurchaseDate().toString())) {
                aDouble = Double.valueOf((date.getTime() - fmDeviceinfo.getPurchaseDate().getTime())) / (1000 * 3600 * 24);
            } else if (datalimit1bydbid != null) {
                aDouble = Double.valueOf((date.getTime() - datalimit1bydbid.getDate().getTime())) / (1000 * 3600 * 24);
                Long a = (date.getTime() - datalimit1bydbid.getDate().getTime());

            }
            //  }
            if (aDouble != 0.0) {
                //查询 drools表是否有这个数据
                OmDrools omDroolsbydbId = omMapper.getOmDroolsbydbId(omRuntimedtl.getDbid(), "maintain");
                if (omDroolsbydbId == null) {
                    omDroolsbydbId = new OmDrools();
                    omDroolsbydbId.setDevName(omRuntimedtl.getName());
                    omDroolsbydbId.setDbId(omRuntimedtl.getDbid());
                    omDroolsbydbId.setHandle(false);
                    omDroolsbydbId.setMaintainType("maintain");
                    omDroolsbydbId.setVariableName(omRuntimedtl.getVariableName());
                    omDroolsbydbId.setVarId(omRuntimedtl.getVarId());

                    //存入
                    omMapper.insertOmDrools(omDroolsbydbId);
                }
                DroolsTest droolsTest = new DroolsTest();
                //如果一条规则判断完成之后不关闭会导致 之后的规则全部能通过
                if (kieHelper != null) {
                    KieSession kieSession = kieHelper.build().newKieSession();

                    droolsTest.setPointName(omRuntimedtl.getName());
                    droolsTest.setKey("定期保养");
                    droolsTest.setVariable("依据公历日自动计算");
                    //相减
                    droolsTest.setValue((float) ((aDouble) - omDroolsbydbId.getRunTime()));
                    droolsTest.setDbId(omRuntimedtl.getDbid());

//            droolsTest.setSingal((String) Beanmap.get("dbid"));


                    kieSession.insert(droolsTest);
                    //执行
                    kieSession.fireAllRules();

                    //关闭
                    kieSession.dispose();
                    if (droolsTest.getSave()) {
                        //运行时长表  规则判断   当前运行了多长时间
                        this.send(omRuntimedtl, droolsTest, aDouble, fmDeviceinfo, "maintain");
                    }
                }


            }
//             aDouble = omMapper.selectdevRuntime(omRuntimedtl.getDbid());

        }
    }

    //寿命到期 判断 修改寿命到期应时间的存在修改
    public void EndofLifetype(List<omRuntimeDtl> onoffdtls, KieHelper kieHelper) throws MqttException, ParseException {

        for (omRuntimeDtl omRuntimedtl : onoffdtls) {
            Date date = new Date();
            Double aDouble = 0.0;
            //查询这个设备的寿命到期时间
            List<SeRuleFile> seRuleFiles = fileMapper.selectMaintainbyname(omRuntimedtl.getName().split(" ")[0]);
            if (seRuleFiles.size() != 0) {

                if (seRuleFiles.get(0).getLifedata() != null) {


                    //计算寿命到期时间
                    aDouble = Double.valueOf((sdf01.parse(seRuleFiles.get(0).getLifedata()).getTime() - date.getTime()) / (1000 * 3600 * 24));
                    fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(omRuntimedtl.getDbid()), String.valueOf(omRuntimedtl.getModelId()));
//
//            omRuntimeDtl datalimit1bydbid = omMapper.getDatalimit1byvarId(omRuntimedtl.getVarId());
//           if (null!=fmDevInfo && StringUtils.isNotBlank(fmDevInfo.getPurchaseDate().toString())){
//               aDouble = Double.valueOf((date.getTime() - fmDevInfo.getPurchaseDate().getTime()) / (1000 * 3600 * 24));
//           }else if (datalimit1bydbid != null) {
//                aDouble = Double.valueOf((date.getTime() - datalimit1bydbid.getDate().getTime()) / (1000 * 3600 * 24));
//            }
                    //     }
                    //   if (aDouble != 0.0) {
                    //查询 drools表是否有这个数据
                    OmDrools omDroolsbydbId = omMapper.getOmDroolsbydbId(omRuntimedtl.getDbid(), "EndofLife");
                    if (omDroolsbydbId == null) {
                        omDroolsbydbId = new OmDrools();
                        omDroolsbydbId.setDevName(omRuntimedtl.getName());
                        omDroolsbydbId.setDbId(omRuntimedtl.getDbid());
                        omDroolsbydbId.setHandle(false);
                        omDroolsbydbId.setMaintainType("EndofLife");
                        omDroolsbydbId.setVariableName(omRuntimedtl.getVariableName());
                        omDroolsbydbId.setVarId(omRuntimedtl.getVarId());
                        //存入
                        omMapper.insertOmDrools(omDroolsbydbId);
                    }
                    DroolsTest droolsTest = new DroolsTest();
                    //如果一条规则判断完成之后不关闭会导致 之后的规则全部能通过
                    if (kieHelper != null) {
                        KieSession kieSession = kieHelper.build().newKieSession();

                        droolsTest.setPointName(omRuntimedtl.getName());
                        droolsTest.setKey("寿命到期");

                        //相减 寿命到期用来判断时间超出多少
                        if (aDouble < 0) {
                            droolsTest.setValue((float) (aDouble - 0.0));
                        } else {
                            droolsTest.setValue((float) ((aDouble) - omDroolsbydbId.getRunTime()));
                        }
                        droolsTest.setDbId(omRuntimedtl.getDbid());
                        droolsTest.setVariable(seRuleFiles.get(0).getLifedata());
//            droolsTest.setSingal((String) Beanmap.get("dbid"));


                        kieSession.insert(droolsTest);
                        //执行
                        kieSession.fireAllRules();

                        //关闭
                        kieSession.dispose();
                        if (droolsTest.getSave()) {
                            //运行时长表  规则判断   当前运行了多长时间
                            this.send(omRuntimedtl, droolsTest, aDouble, fmDeviceinfo, "EndofLife");
                        }
                        //       }

                    }

                }
//             aDouble = omMapper.selectdevRuntime(omRuntimedtl.getDbid());
            }
        }

    }

    //寿命到期 判断 修改寿命到期应时间的存在修改
    public void EndofLifeexample(List<omRuntimeDtl> onoffdtls, KieHelper kieHelper) throws MqttException, ParseException {

        for (omRuntimeDtl omRuntimedtl : onoffdtls) {
            Date date = new Date();
            Double aDouble = 0.0;
            //查询这个设备的寿命到期时间
            List<SeRuleFile> seRuleFiles = fileMapper.selectbydbidandalarmtype(omRuntimedtl.getDbid());
            if (seRuleFiles.size() != 0) {
                if (seRuleFiles.get(0).getLifedata() != null) {


                    //计算寿命到期时间
                    aDouble = Double.valueOf((sdf01.parse(seRuleFiles.get(0).getLifedata()).getTime() - date.getTime()) / (1000 * 3600 * 24));
                    fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(omRuntimedtl.getDbid()), String.valueOf(omRuntimedtl.getModelId()));
//
//            omRuntimeDtl datalimit1bydbid = omMapper.getDatalimit1byvarId(omRuntimedtl.getVarId());
//           if (null!=fmDevInfo && StringUtils.isNotBlank(fmDevInfo.getPurchaseDate().toString())){
//               aDouble = Double.valueOf((date.getTime() - fmDevInfo.getPurchaseDate().getTime()) / (1000 * 3600 * 24));
//           }else if (datalimit1bydbid != null) {
//                aDouble = Double.valueOf((date.getTime() - datalimit1bydbid.getDate().getTime()) / (1000 * 3600 * 24));
//            }
                    //     }
                    //     if (aDouble != 0.0) {
                    //查询 drools表是否有这个数据
                    OmDrools omDroolsbydbId = omMapper.getOmDroolsbydbId(omRuntimedtl.getDbid(), "EndofLife");
                    if (omDroolsbydbId == null) {
                        omDroolsbydbId = new OmDrools();
                        omDroolsbydbId.setDevName(omRuntimedtl.getName());
                        omDroolsbydbId.setDbId(omRuntimedtl.getDbid());
                        omDroolsbydbId.setHandle(false);
                        omDroolsbydbId.setMaintainType("EndofLife");
                        omDroolsbydbId.setVariableName(omRuntimedtl.getVariableName());
                        omDroolsbydbId.setVarId(omRuntimedtl.getVarId());
                        //存入
                        omMapper.insertOmDrools(omDroolsbydbId);
                    }
                    DroolsTest droolsTest = new DroolsTest();
                    //如果一条规则判断完成之后不关闭会导致 之后的规则全部能通过
                    if (kieHelper != null) {
                        KieSession kieSession = kieHelper.build().newKieSession();

                        droolsTest.setPointName(omRuntimedtl.getName());
                        droolsTest.setKey("寿命到期");
                        //相减 寿命到期用来判断时间超出多少
                        droolsTest.setValue((float) (aDouble - 0.0));
//                    if (aDouble < 0) {
//                        droolsTest.setValue((float) (aDouble - 0.0));
//                    } else {
//                        droolsTest.setValue((float) ((aDouble) - omDroolsbydbId.getRunTime()));
//                    }

                        droolsTest.setDbId(omRuntimedtl.getDbid());
                        droolsTest.setVariable(seRuleFiles.get(0).getLifedata());
//            droolsTest.setSingal((String) Beanmap.get("dbid"));


                        kieSession.insert(droolsTest);
                        //执行
                        kieSession.fireAllRules();

                        //关闭
                        kieSession.dispose();
                        if (droolsTest.getSave()) {
                            //运行时长表  规则判断   当前运行了多长时间
                            this.send(omRuntimedtl, droolsTest, aDouble, fmDeviceinfo, "EndofLife");
                        }
                        //         }

                    }
                }
//             aDouble = omMapper.selectdevRuntime(omRuntimedtl.getDbid());
            }
        }

    }

    //运行时长 判断
    public void runtimekie(List<omRuntimeDtl> onoffdtls, KieHelper kieHelper) throws MqttException {
        for (omRuntimeDtl omRuntimedtl : onoffdtls) {
            //查询这个设备的运行时长
            Double aDouble = omMapper.selectdevRuntime(omRuntimedtl.getVarId());
            //查询 drools表是否有这个数据
            //OmDrools omDroolsbydbId = omMapper.getOmDroolsbydbIdandposition(omRuntimedtl.getDbid(),"Runtime",omRuntimedtl.getVariableName());
            OmDrools omDroolsbydbId = omMapper.getOmDroolsbydbIdandposition(omRuntimedtl.getDbid(), "Runtime", omRuntimedtl.getVarId());
            if (omDroolsbydbId == null) {
                omDroolsbydbId = new OmDrools();
                omDroolsbydbId.setDevName(omRuntimedtl.getName());
                omDroolsbydbId.setDbId(omRuntimedtl.getDbid());
                omDroolsbydbId.setHandle(false);
                omDroolsbydbId.setMaintainType("Runtime");
                omDroolsbydbId.setVariableName(omRuntimedtl.getVariableName());
                omDroolsbydbId.setVarId(omRuntimedtl.getVarId());
                //存入
                omMapper.insertOmDrools(omDroolsbydbId);
            }
            DroolsTest droolsTest = new DroolsTest();
            //如果一条规则判断完成之后不关闭会导致 之后的规则全部能通过
            if (kieHelper != null) {
                KieSession kieSession = kieHelper.build().newKieSession();

                droolsTest.setPointName(omRuntimedtl.getName() + "");
                droolsTest.setKey("运行时长");
                //相减
                droolsTest.setValue((float) ((aDouble / 3600) - omDroolsbydbId.getRunTime()));
                droolsTest.setDbId(omRuntimedtl.getDbid());
//            droolsTest.setSingal((String) Beanmap.get("dbid"));
                droolsTest.setVariable(omRuntimedtl.getVariableName());

                kieSession.insert(droolsTest);
                //执行
                kieSession.fireAllRules();

                //关闭
                kieSession.dispose();
                if (droolsTest.getSave()) {
                    fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(omRuntimedtl.getDbid()), String.valueOf(omRuntimedtl.getModelId()));
                    //运行时长表  规则判断   当前运行了多长时间
                    this.send(omRuntimedtl, droolsTest, aDouble, fmDeviceinfo, "Runtime");
                }
            }

        }
    }

    // 保修到期
    public void maintenancetype(List<omRuntimeDtl> onoffdtls, KieHelper kieHelper) throws MqttException, ParseException {

        for (omRuntimeDtl omRuntimedtl : onoffdtls) {
            Date date = new Date();
            Double aDouble = 0.0;
            //查询这个设备的寿命到期时间
            List<SeRuleFile> seRuleFiles = fileMapper.selectbydbidandalarmtype(omRuntimedtl.getDbid());
            if (seRuleFiles.size() != 0) {
                if (seRuleFiles.get(0).getMaintenancedata() != null) {
                    //计算寿命到期时间
                    aDouble = Double.valueOf((sdf01.parse(seRuleFiles.get(0).getMaintenancedata()).getTime() - date.getTime()) / (1000 * 3600 * 24));
                    fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(omRuntimedtl.getDbid()), String.valueOf(omRuntimedtl.getModelId()));
//
//            omRuntimeDtl datalimit1bydbid = omMapper.getDatalimit1byvarId(omRuntimedtl.getVarId());
//           if (null!=fmDevInfo && StringUtils.isNotBlank(fmDevInfo.getPurchaseDate().toString())){
//               aDouble = Double.valueOf((date.getTime() - fmDevInfo.getPurchaseDate().getTime()) / (1000 * 3600 * 24));
//           }else if (datalimit1bydbid != null) {
//                aDouble = Double.valueOf((date.getTime() - datalimit1bydbid.getDate().getTime()) / (1000 * 3600 * 24));
//            }
                    //     }
                    //     if (aDouble != 0.0) {
                    //查询 drools表是否有这个数据
                    OmDrools omDroolsbydbId = omMapper.getOmDroolsbydbId(omRuntimedtl.getDbid(), "Maintenance");
                    if (omDroolsbydbId == null) {
                        omDroolsbydbId = new OmDrools();
                        omDroolsbydbId.setDevName(omRuntimedtl.getName());
                        omDroolsbydbId.setDbId(omRuntimedtl.getDbid());
                        omDroolsbydbId.setHandle(false);
                        omDroolsbydbId.setMaintainType("Maintenance");
                        omDroolsbydbId.setVariableName(omRuntimedtl.getVariableName());
                        omDroolsbydbId.setVarId(omRuntimedtl.getVarId());
                        //存入
                        omMapper.insertOmDrools(omDroolsbydbId);
                    }
                    DroolsTest droolsTest = new DroolsTest();
                    //如果一条规则判断完成之后不关闭会导致 之后的规则全部能通过
                    if (kieHelper != null) {
                        KieSession kieSession = kieHelper.build().newKieSession();

                        droolsTest.setPointName(omRuntimedtl.getName());
                        droolsTest.setKey("保修到期");
                        //相减 寿命到期用来判断时间超出多少
                        droolsTest.setValue((float) (aDouble - 0.0));
//                    if (aDouble < 0) {
//                        droolsTest.setValue((float) (aDouble - 0.0));
//                    } else {
//                        droolsTest.setValue((float) ((aDouble) - omDroolsbydbId.getRunTime()));
//                    }

                        droolsTest.setDbId(omRuntimedtl.getDbid());
                        droolsTest.setVariable(seRuleFiles.get(0).getMaintenancedata());
//            droolsTest.setSingal((String) Beanmap.get("dbid"));


                        kieSession.insert(droolsTest);
                        //执行
                        kieSession.fireAllRules();

                        //关闭
                        kieSession.dispose();
                        if (droolsTest.getSave()) {
                            //运行时长表  规则判断   当前运行了多长时间
                            this.send(omRuntimedtl, droolsTest, aDouble, fmDeviceinfo, "Maintenance");
                        }
                        //         }

                    }

//             aDouble = omMapper.selectdevRuntime(omRuntimedtl.getDbid());
                }
            }
        }
    }

    public void maintenanceexample(List<omRuntimeDtl> onoffdtls, KieHelper kieHelper) throws MqttException, ParseException {

        for (omRuntimeDtl omRuntimedtl : onoffdtls) {
            Date date = new Date();
            Double aDouble = 0.0;
            //查询这个设备的寿命到期时间
            List<SeRuleFile> seRuleFiles = fileMapper.selectbydbidandalarmtype(omRuntimedtl.getDbid());
            if (seRuleFiles.size() != 0) {
                if (seRuleFiles.get(0).getMaintenancedata() != null) {
                    //计算寿命到期时间
                    aDouble = Double.valueOf((sdf01.parse(seRuleFiles.get(0).getMaintenancedata()).getTime() - date.getTime()) / (1000 * 3600 * 24));
                    fmDevInfo fmDeviceinfo = infoMapper.selectdevicebyobjectId(String.valueOf(omRuntimedtl.getDbid()), String.valueOf(omRuntimedtl.getModelId()));
//
//            omRuntimeDtl datalimit1bydbid = omMapper.getDatalimit1byvarId(omRuntimedtl.getVarId());
//           if (null!=fmDevInfo && StringUtils.isNotBlank(fmDevInfo.getPurchaseDate().toString())){
//               aDouble = Double.valueOf((date.getTime() - fmDevInfo.getPurchaseDate().getTime()) / (1000 * 3600 * 24));
//           }else if (datalimit1bydbid != null) {
//                aDouble = Double.valueOf((date.getTime() - datalimit1bydbid.getDate().getTime()) / (1000 * 3600 * 24));
//            }
                    //     }
                    //     if (aDouble != 0.0) {
                    //查询 drools表是否有这个数据
                    OmDrools omDroolsbydbId = omMapper.getOmDroolsbydbId(omRuntimedtl.getDbid(), "Maintenance");
                    if (omDroolsbydbId == null) {
                        omDroolsbydbId = new OmDrools();
                        omDroolsbydbId.setDevName(omRuntimedtl.getName());
                        omDroolsbydbId.setDbId(omRuntimedtl.getDbid());
                        omDroolsbydbId.setHandle(false);
                        omDroolsbydbId.setMaintainType("Maintenance");
                        omDroolsbydbId.setVariableName(omRuntimedtl.getVariableName());
                        omDroolsbydbId.setVarId(omRuntimedtl.getVarId());
                        //存入
                        omMapper.insertOmDrools(omDroolsbydbId);
                    }
                    DroolsTest droolsTest = new DroolsTest();
                    //如果一条规则判断完成之后不关闭会导致 之后的规则全部能通过
                    if (kieHelper != null) {
                        KieSession kieSession = kieHelper.build().newKieSession();

                        droolsTest.setPointName(omRuntimedtl.getName());
                        droolsTest.setKey("保修到期");
                        //相减 寿命到期用来判断时间超出多少
                        droolsTest.setValue((float) (aDouble - 0.0));
//                    if (aDouble < 0) {
//                        droolsTest.setValue((float) (aDouble - 0.0));
//                    } else {
//                        droolsTest.setValue((float) ((aDouble) - omDroolsbydbId.getRunTime()));
//                    }

                        droolsTest.setDbId(omRuntimedtl.getDbid());
                        droolsTest.setVariable(seRuleFiles.get(0).getMaintenancedata());
//            droolsTest.setSingal((String) Beanmap.get("dbid"));


                        kieSession.insert(droolsTest);
                        //执行
                        kieSession.fireAllRules();

                        //关闭
                        kieSession.dispose();
                        if (droolsTest.getSave()) {
                            //运行时长表  规则判断   当前运行了多长时间
                            this.send(omRuntimedtl, droolsTest, aDouble, fmDeviceinfo, "Maintenance");
                        }
                        //         }

                    }
                }
//             aDouble = omMapper.selectdevRuntime(omRuntimedtl.getDbid());
            }
        }

    }


    public void send(omRuntimeDtl omRuntimedtl, DroolsTest droolsTest, Double aDouble, fmDevInfo fmDeviceinfo, String type) throws MqttException {
        //修改这个设备的时间

        //查询设备

        //修改 记录表  一个sql就可以懒得改了
        OmDrools omDrools = null;
        if (StringUtils.isNotBlank(omRuntimedtl.getVariableName())) {
            omDrools = omMapper.getOmDroolsbydbIdandposition(omRuntimedtl.getDbid(), type, omRuntimedtl.getVarId());
        } else {
            omDrools = omMapper.getOmDroolsbydbId(omRuntimedtl.getDbid(), type);
        }

//        if (omDrools.getHandle()){
        omDrools.setDevName(omRuntimedtl.getName());
        omDrools.setDbId(omRuntimedtl.getDbid());
        omDrools.setMaintainType(type);
        omDrools.setHandle(false);
//            omDrools.setPosition(omRuntimedtl.getPosition());
        if ("Runtime".equals(type)) {
            omDrools.setRunTime((aDouble / 3600));

        } else {
            omDrools.setRunTime(aDouble);
        }

        //修改
        if (StringUtils.isNotBlank(omRuntimedtl.getVariableName())) {
            omMapper.updateOmDroolsbyposition(omDrools);
        } else {
            omMapper.updateOmDrools(omDrools);
        }


        //报警记录表
        msgDevice msgDevice = new msgDevice();
        msgDevice.setDbId(droolsTest.getDbId());
        //  msgDevice.setAlarmValue(", 当前值为" + String.valueOf(droolsTest.getValue()));

        String dateString = formatter.format(new Date());
        msgDevice.setAlarmTime(dateString);
        msgDevice.setIsNew(1);
        msgDevice.setIsHandle(0);
        msgDevice.setAlarmDescription(droolsTest.getInformation());
        msgDevice.setAlarmStatus(droolsTest.getMessageType());
        //  msgDevice.setComId(serComAddr.getAlarmFeatures());

        //为null 是设备
        msgDevice.setDevLocation(fmDeviceinfo.getDevLocation());
        msgDevice.setDevName(fmDeviceinfo.getDevName());
//        if ("Runtime".equals(type)) {
//            msgDevice.setAlarmType(droolsTest.getInformation());
//        } else
        if ("EndofLife".equals(type) || "Maintenance".equals(type)) {
            //单独计算寿命到期提醒内容
            if (droolsTest.getValue() < 0) {
                msgDevice.setAlarmDescription(droolsTest.getPointName() + "寿命已超出" + Math.abs(droolsTest.getValue()) + "天");
            } else {
                msgDevice.setAlarmDescription(droolsTest.getPointName() + "还剩余" + droolsTest.getValue() + "天使用寿命");
            }


        }
        msgDevice.setAlarmType("设备维保提醒");
//    wei } else if ("Maintenance".equals(type)) {
//            msgDevice.setAlarmType("维保保养提醒");
//        } else {
//            msgDevice.setAlarmType("维保报警提醒");
//        }

        msgDevice.setDevNumber(fmDeviceinfo.getDevNumber());
        msgDevice.setAlarmStatus("保养");
        //msgDevice.setVarId(serComAddr.getVariableId());
        msgDevice.setSystemName(fmDeviceinfo.getSystemBelong());
        msgDevice.setRemindType("微信提醒");
        msgDevice.setAlarmGrade(droolsTest.getMessagelevel());

        //  msgDevice.setVarType(serComAddr.getVariableType());
        // msgDevice.setSingal(droolsTest.getSingal());
        msgDevice.setSubsystemName(fmDeviceinfo.getSubsystemBelong());

        msgDevice.setLevel(fmDeviceinfo.getDevLevel());
        msgDevice.setModelId(fmDeviceinfo.getModelId());
        msgDevice.setAlarmCount(0);
        msgDevice.setAlarmVar(droolsTest.getVariable());
//            msgDevice.setPosition(omRuntimedtl.getPosition());

        //前端用来区分是保养还是报警
        msgDevice.setMsgType("maintain");
        msgDevice.setType("dev");

        //是否只存一条?
//        msgDevice msgDevice1 = alarmMapper.getbydbIdmodelIDandvar(msgDevice.getDbId(), msgDevice.getAlarmVar(), msgDevice.getModelId());
//        if (msgDevice1!=null){
//            alarmMapper.insertAlarm(msgDevice);
//        }
        alarmMapper.insertAlarm(msgDevice);
        //发送类型前端区分 是什么报警
        HashMap<Object, Object> alarmMap = new HashMap<>();

        alarmMessage alarmMessage = new alarmMessage();
//            alarmMessage.setAlarmType("保养");
        alarmMessage.setMaintainType(type);
        alarmMessage.setDbId(fmDeviceinfo.getObjectId());
        alarmMap.put("maintain", alarmMessage);
        //


        //消息提醒存储
        messageRemind messageRemind = new messageRemind();
        messageRemind.setAlarmId(msgDevice.getId());
        //设备报警
        messageRemind.setOrderType("设备保养提醒");
        messageRemind.setDevLocation(fmDeviceinfo.getDevLocation());
        messageRemind.setDevName(fmDeviceinfo.getDevName());
        messageRemind.setDevNumber(fmDeviceinfo.getDevNumber());
        messageRemind.setFaultLevel(droolsTest.getMessagelevel());
        messageRemind.setDescription(msgDevice.getAlarmDescription());
        if (droolsTest.getPosition() != null) {
            messageRemind.setMaintainPosition(droolsTest.getPosition());
        }
        messageRemind.setLastrecialamtime(new Date());
        messageRemind.setIsReset(false);
        messageRemind.setAlarmType("maintain");
        messageRemind.setDbId(Integer.parseInt(fmDeviceinfo.getObjectId()));
        messageRemind.setModelId(Integer.parseInt(fmDeviceinfo.getModelId()));
        messageRemind.setAlarmnumber(1);
        messageRemind.setSubsystemBelong(fmDeviceinfo.getSubsystemBelong());
        messageRemind.setSystemBelong(fmDeviceinfo.getSystemBelong());
        messageRemind.setLocation(fmDeviceinfo.getDevLocation());
        messageRemind.setAlarmVar(msgDevice.getAlarmVar());
        messageRemind.setType("dev");
        messageRemind.setAlarmSatus("保养");
        //    messageRemind select = messageRemindMapper.selectbymaintainPosition(messageRemind);

//        if (select != null) {
//            messageRemind.setId(select.getId());
//            messageRemindMapper.updatalarmnumberbyPosition(messageRemind);
//        } else {
        messageRemindMapper.insertmessageRemind(messageRemind);
        //    }

        //  WebSocketServerRemind.sendMessage(JSONArray.toJSONString(alarmMap));


//        ArrayList<alarmMessage> alarmMessages = new ArrayList<>();
//
//        HashMap<Object, Object> mapss = new HashMap<>();
//
        HashMap<String, Object> map = new HashMap<>();
//        //用来区分模板
//        map.put("sendtype", type);
//        map.put("type", "dev");
//        map.put("subsystemBelong", fmDevInfo.getSystemBelong());
//        map.put("systemBelong", fmDevInfo.getSubsystemBelong());
//        map.put("sname", fmDevInfo.getDevName());
//        map.put("number", fmDevInfo.getDevNumber());
//        map.put("level", fmDevInfo.getDevLevel());
//        map.put("messagelevel", droolsTest.getMessagelevel());
//        map.put("information", droolsTest.getInformation());
//        map.put("storey", fmDevInfo.getDevLocation());
//        SimpleDateFormat sdf01 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("data", messageRemind);

        serviceMQTT.alarm(map);
    }


    //  }


}
